﻿using System;
using System.Text;
using Autofac.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json.Serialization;
using NLog.Extensions.Logging;
using NLog.Web;
using Ubiquity.Web.Filters;
using Ubiquity.Web.Ioc;

namespace Ubiquity.Web
{


    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            var builder = new ConfigurationBuilder()
                .SetBasePath(Environment.CurrentDirectory)
                .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                //.AddJsonFile("Configs/appsettings.json", optional: true, reloadOnChange: true)
                ;
            Configuration = builder.Build();

            //var builder = new ConfigurationBuilder()
            //    .SetBasePath(env.ContentRootPath)
            //    .AddCacheFile("Configs/cacheSettings.json", optional: false)
            //    .AddJsonFile("Configs/appsettings.json", optional: true, reloadOnChange: true)
            //    .AddGatewayFile("Configs/gatewaySettings.json", optional: false)
            //    .AddJsonFile($"Configs/appsettings.{env.EnvironmentName}.json", optional: true);

            // Configuration = configuration;
        }

        public IConfiguration Configuration { get; }
        // This method gets called by the runtime. Use this method to add services to the container.
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            services.Configure<CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            services
                .AddMvc(options =>
                        {
                            options.Filters.Add<ErrorFilter>();//注册 异常拦截器
                        })
                .SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
                .AddJsonOptions(options =>
                {
                    //options.SerializerSettings.ContractResolver = new DefaultContractResolver();
                    //options.SerializerSettings.DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc;
                    //options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
                })
                  ;

            //  services.AddMemoryCache();  //IMemoryCache

            //   services.Configure<Configuration>(Configuration);
            services.AddDistributedMemoryCache();
            services.AddSession();




            #region Ioc  配置

            var builder = IocConfig.Build();
            //将services中的服务填充到Autofac中.
            builder.Populate(services);


            //创建容器.
            IocConfig.AutofacContainer = builder.Build();
            //使用容器创建 AutofacServiceProvider 
            return new AutofacServiceProvider(IocConfig.AutofacContainer);
            #endregion

        }


        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IApplicationLifetime appLifetime)
        {

            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);//这是为了防止中文乱码

            loggerFactory.AddNLog();//添加NLog
                                    //loggerFactory.AddNLog();
                                    //loggerFactory.AddDebug();

            //引入Nlog配置文件
            env.ConfigureNLog("Configs/nlog.config");

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseCookiePolicy();

            app.UseSession();//UseSession配置在UseMvc之前




            //if (!string.IsNullOrEmpty(GlobalContext.SystemConfig.VirtualDirectory))
            //{
            //    app.UsePathBase(new PathString(GlobalContext.SystemConfig.VirtualDirectory)); // 让 Pathbase 中间件成为第一个处理请求的中间件， 才能正确的模拟虚拟路径
            //}
            //if (env.IsDevelopment())
            //{
            //    GlobalContext.SystemConfig.Debug = true;
            //    app.UseDeveloperExceptionPage();
            //}
            //else
            //{
            //    app.UseExceptionHandler("/Home/Error");
            //}
            app.UseStaticFiles();

            //app.Use()
            app.UseRouting();

            app.UseAuthentication();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");

                endpoints.MapControllerRoute(
                    name: "areas",
                    pattern: "{area:exists}/{controller=Login}/{action=Index}/{id?}");
                        //    routes.MapRoute(
                //        name: "areas",
                //        template: "{area:exists}/{controller=Home}/{action=Index}/{id?}"
                //    );

            });

            //app.UseMvc(routes =>
            //{
            //    routes.MapRoute(
            //        name: "default",
            //        template: "{controller=Home}/{action=Index}/{id?}");
            //});
            //app.UseMvc(routes =>
            //{
            //    routes.MapRoute(
            //        name: "areas",
            //        template: "{area:exists}/{controller=Home}/{action=Index}/{id?}"
            //    );
            //});

            ////程序停止调用函数 Ioc
            //appLifetime.ApplicationStopped.Register(() =>
            //{
            //    AutofacContainer.Dispose();
            //});
        }



    }
}
